import express from 'express'
import proxy from 'express-http-proxy'
import { matchRoutes } from 'react-router-config'
import { getStore } from '../store'
import { render } from './utils'
import routes from '../Routes'

const app = express()
app.use(express.static("public"));

app.use('/api',proxy('http://47.95.113.63', {
  proxyReqPathResolver: function (req) {
    // var parts = req.url.split('?');
    // var queryString = parts[1];
    // var updatedPath = parts[0].replace(/test/, 'tent');
    return '/ssr/api'+ req.url
  }
}));

app.get('*', function (req, res) {
  const context = { css: [] }
  const store = getStore(req)
  const matchedRoutes = matchRoutes(routes, req.path)
  const promises = []
  matchedRoutes.forEach((item) => {
    if (item.route.loadData) {
      const promise = new Promise((resolve) => {
        item.route.loadData(store).then(resolve).catch(resolve)
      })
      promises.push(promise)
    }
  })
  Promise.all(promises).then(() => {
    const html = render(store, routes, req, context)
    if (context.action === 'REPLACE') {
      res.redirect(301,context.url)
    }else if(context.NOT_FOUND){
      res.status(404)
      res.send(html)
    }else{
      res.send(html)
    }
  })
})


app.listen(3000, function () {
  console.log('成功的启动在3000端口')
})
